package com.graduation_design.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation_design.common.dto.AppSkuDto;
import com.graduation_design.common.exception.HubException;
import com.graduation_design.entity.*;
import com.graduation_design.mapper.AppProductMapper;
import com.graduation_design.service.AppOrderItemService;
import com.graduation_design.service.AppSkuStockService;
import com.graduation_design.mapper.AppSkuStockMapper;
import com.graduation_design.service.AppSpecificationService;
import com.graduation_design.service.AppSpecificationValueService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 从南
* @description 针对表【app_sku_stock】的数据库操作Service实现
* @createDate 2024-02-16 18:15:59
*/
@Service
public class AppSkuStockServiceImpl extends ServiceImpl<AppSkuStockMapper, AppSkuStock>
    implements AppSkuStockService{

    @Resource
    AppProductMapper appProductMapper;

    @Resource
    AppSkuStockMapper appSkuStockMapper;

    @Resource
    AppOrderItemService appOrderItemService;

    @Resource
    AppSpecificationService appSpecificationService;

    @Resource
    AppSpecificationValueService appSpecificationValueService;

    /**
     * sku规格组合
     */
    @Override
    public List<AppSkuStock> listSkuByProductId(Long productId) {
        List<AppSkuStock> skuStocks = this.list(
                new QueryWrapper<AppSkuStock>().eq("product_id", productId)
        );

//        skuStocks.stream().forEach(sku -> {
//            sku.setSpecs(Arrays.asList(sku.getSku().split(";")));
//        });

        return skuStocks.size() > 0 ? skuStocks : ListUtil.toList(getSingleSku(productId));
    }

    /**
     * 获取商品的规格
     * 商品有规格记录的时候，库存记录在规格表中，当商品是默认规格时候，库存就是商品表中的。
     */
    @Override
    public AppSkuStock getSku(Long skuId, Long productId) {
        if (skuId != -1) {
            // 多规格库存
            return this.getById(skuId);
        }
        // 单规格库存
        return getSingleSku(productId);
    }

    /**
     * 判断库存并扣减库存
     * @param orderItems
     */
    @Override
    public void reduceStock(List<AppOrderItem> orderItems) {

        System.out.println("开始减库存操作");

        orderItems.forEach(orderItem -> {
            int count;
            if (orderItem.getSkuId() == -1) {
                // 默认规格
                count = appProductMapper.reduceStock(orderItem.getProductId(), orderItem.getQuantity());
                if (count == 0) {
                    throw new HubException("库存不足");
                }
                System.out.println(orderItem.getProductId() + " - 默认规格  " + count);

            } else {
                // 多规格
                count = appSkuStockMapper.reduceStock(orderItem.getSkuId(), orderItem.getQuantity());
                if (count == 0) {
                    throw new HubException("库存不足");
                }
                System.out.println(orderItem.getSkuId() + " - 多规格  " + count);

            }
            if (count < 1) {
                throw new HubException("减库存操作失败");
            }
        });
    }

    /**
     * 订单取消
     */
    @Override
    public void releaseStock(AppOrder appOrder) {
        System.out.println("开始加库存操作");

        if (appOrder.getOrderItems() == null) {
            appOrder.setOrderItems(appOrderItemService.listByOrderId(appOrder.getId()));
        }
        appOrder.getOrderItems().forEach(orderItem -> {
            int count;
            if (orderItem.getSkuId() == -1) {
                // 默认规格
                count = appProductMapper.releaseStock(orderItem.getProductId(), orderItem.getQuantity());
                System.out.println(orderItem.getProductId() + " - 默认规格  " + count);

            } else {
                // 多规格
                count = appSkuStockMapper.releaseStock(orderItem.getSkuId(), orderItem.getQuantity());
                System.out.println(orderItem.getSkuId() + " - 多规格  " + count);

            }
            if (count < 1) {
                throw new HubException("释放库存操作失败");
            }
        });
    }

    @Override
    public Object getSkuByProductId(Long productId) {

        // 商品信息
        AppProduct appProduct = appProductMapper.selectById(productId);
        Assert.notNull(appProduct, "商品不存在");
        // 商品属性
        List<AppSpecification> specifications = appSpecificationService.list();

        // 商品规格 [{ spec: "颜色", values: ["红色", "紫色", "白色", "黑色"] }]
        List<AppSpecificationValue> specificationValues = appSpecificationValueService.list(new QueryWrapper<AppSpecificationValue>()
                .eq("product_id", productId)
        );

        // 获取规格值的名称组合
        List<String> selectSpecValues = specificationValues.stream().map(AppSpecificationValue::getSpec).collect(Collectors.toList());

        // 获取商品sku信息
        List<AppSkuStock> skuStocks = this.listSkuByProductId(productId);

        return MapUtil.builder()
                .put("product", appProduct)
                .put("skuStocks", skuStocks)
                .put("specValues", specificationValues)
                .put("specs", specifications)
                .put("selectSpecValues", selectSpecValues)
                .build();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSku(AppSkuDto appSkuDto) {
        Assert.notNull(appSkuDto.getProductId(), "参数异常，请稍后再试");

        // 处理sku
        List<AppSkuStock> appSkuStocks = appSkuDto.getSkuStocks();
        if (appSkuStocks != null && appSkuStocks.size() > 0) {
            appSkuStocks.forEach(appSkuStock -> {
                if (appSkuStock.getId() == null) {
                    appSkuStock.setCreated(LocalDateTime.now());
                } else {
                    appSkuStock.setUpdated(LocalDateTime.now());
                }
            });
            this.saveOrUpdateBatch(appSkuStocks);
        }
        // 删除多余的sku
        List<Long> skuIds = appSkuStocks.stream().map(AppSkuStock::getId).collect(Collectors.toList());
        this.remove(new QueryWrapper<AppSkuStock>()
                .eq("product_id", appSkuDto.getProductId())
                .notIn(!skuIds.isEmpty(), "id", skuIds) // 为空情况，就全删了
        );


        // 处理specValue 保存商品规格值
        List<AppSpecificationValue> specValues = appSkuDto.getSpecValues();
        // 先删除之前的，再添加新的
        appSpecificationValueService.remove(new QueryWrapper<AppSpecificationValue>()
                .eq("product_id", appSkuDto.getProductId()));
        if (specValues == null || specValues.size() == 0) {
            System.out.println("默认specValue，不需要保存 -- " + appSkuDto.getProductId());
        } else{
            specValues.forEach(e -> e.setCreated(LocalDateTime.now()));
            appSpecificationValueService.saveBatch(specValues);
        }
    }

    /**
     * 单一规格
     */
    private AppSkuStock getSingleSku(Long productId) {
        AppProduct product = appProductMapper.selectById(productId);

        AppSkuStock skuStock = new AppSkuStock();
        skuStock.setSku("默认规格");
//        skuStock.setSpecs(ListUtil.toList("默认规格"));
        skuStock.setStock(product.getStock());
        skuStock.setPrice(product.getPrice());
        skuStock.setId(-1L);

        return skuStock;
    }
}




